package org.techmore.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.techmore.R;
import org.techmore.biz.CouponListActivityDataHandler;
import org.techmore.utils.PropertiesUtil;
import org.techmore.zxing.client.android.CaptureActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

@SuppressWarnings("rawtypes")
public class CouponSearchActivity extends Activity {
	private List<Map> cityList;
	ViewGroup couponsearch;
    TableLayout contentTableLayout;
    Button contentSearchButton;
    Button titleSearchButton;
    
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setScreenOrientation();
        setContentScrollViewHeightDynamic();
    }
    
    /**
     * 設置屏幕方向
     */
    private void setScreenOrientation(){
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);		//豎屏
//    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);		//橫屏
    }
    
    /**
     * 設置內容區
     */
   
	@SuppressWarnings("unchecked")
	private void setContentScrollViewHeightDynamic(){
    	cityList = this.getCityList();
    	couponsearch = (ViewGroup)LayoutInflater.from(this).inflate(R.layout.techmore_couponsearch, null);
        contentTableLayout = (TableLayout) couponsearch.findViewById(R.id.contentTableLayout);
        contentSearchButton = (Button) couponsearch.findViewById(R.id.contentSearchButton);
        titleSearchButton = (Button) couponsearch.findViewById(R.id.titleSearchButton);
        
        this.addSearchButtonListener(contentSearchButton);
        this.addSearchButtonListener(titleSearchButton);
        
        contentTableLayout.removeAllViews();
        
        for (Map dataMap : cityList) {
        	contentTableLayout.addView(createTableRow(dataMap));
        	contentTableLayout.addView(createTableRowLine());
		}
        
        setContentView(couponsearch);
        adapterFootButton(couponsearch);
    }
    
    private void addSearchButtonListener(Button button){
    	button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText contentSearchEditText = (EditText)findViewById(R.id.contentSearchEditText);
				String keyword = contentSearchEditText.getText().toString();
				String cityIds = "";
				
		        for (Map dataMap : cityList) {
		        	String cityId = String.valueOf(dataMap.get("cityId"));
		        	CheckBox checkBox = (CheckBox)contentTableLayout.findViewWithTag(cityId);
		        	
		        	if(checkBox.isChecked()){
		        		cityIds += cityId + ",";
		        	}
				}
		        
		        if(cityIds.endsWith(",")){
		        	cityIds = cityIds.substring(0,cityIds.lastIndexOf(","));
		        }
		        
		        String url = PropertiesUtil.getInstance().getValue("qr_seach");
		        if(keyword != null && keyword != ""){
		        	url += "&subject=" + URLEncoder.encode(keyword);
		        }
		        if(keyword != null && keyword != ""){
		        	url += "&cityID=" + cityIds;
		        }
		        
		       
		        if(null != url ){
		        	CouponListActivityDataHandler.getInstance().getCouponListByUrl(CouponSearchActivity.this,url);
		        	
		        }
		        
			}
		});
    }
    
    /**
     * 創建數據行
     * @param index
     * @return
     */
    private View createTableRow(Map dataMap){
		final View rowView = LayoutInflater.from(this).inflate(R.layout.techmore_couponsearch_content_tablerow,null);
		TableRow tableRow = (TableRow) rowView.findViewById(R.id.contentTableRow);
		TextView cityNameTextView = (TextView)tableRow.findViewById(R.id.cityNameTextView);
		CheckBox contentCheckBox = (CheckBox)tableRow.findViewById(R.id.contentCheckBox);
		
		String cityId = String.valueOf(dataMap.get("cityId"));
		String cityName = String.valueOf(dataMap.get("cityName"));
		
//		//設置行數據	
		cityNameTextView.setText(cityName);
		contentCheckBox.setTag(cityId);
		
//		addGotoDetailButtonListener(contentImageButtonRight,String.valueOf(dataMap.get("couponId")));	//為ImageButton添加事件
		
		return rowView;
	}
    
    /**
     * 創建行分割線
     * @return
     */
    private View createTableRowLine(){
    	ViewGroup.LayoutParams linePara = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
    	
    	TextView tvLine = new TextView(this);
    	tvLine.setLayoutParams(linePara);
    	tvLine.setHeight(1);
    	tvLine.setBackgroundColor(Color.GRAY);
    	
    	return tvLine;
    }
    
    private void adapterFootButton(ViewGroup viewGroup){
    	//獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer windowWidth = displayMetrics.widthPixels;
        
    	LinearLayout couponListButton = (LinearLayout) viewGroup.findViewById(R.id.couponListButton);
        LinearLayout nearCouponListButton = (LinearLayout) viewGroup.findViewById(R.id.nearCouponListButton);
    	LinearLayout myCouponListButton = (LinearLayout) viewGroup.findViewById(R.id.myCouponListButton);
    	LinearLayout couponScanner = (LinearLayout) viewGroup.findViewById(R.id.couponScanner);
    	
    	RelativeLayout.LayoutParams layoutParams = null;
    	
    	if(240<windowWidth){
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) nearCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		nearCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) myCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		myCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponScanner.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponScanner.setLayoutParams(layoutParams);
    	}
    	
    	nearCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponSearchActivity.this, CouponMapActivity.class);
				CouponSearchActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    	
    	couponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponSearchActivity.this, CouponListActivity.class);
				CouponSearchActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponSearchActivity.this.finish();
				Log.i("couponListButton", "couponListButton");
				return false;
			}
		});
    	
    	couponScanner.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CouponSearchActivity.this);
				if(preferences.getBoolean("isLogin",false)){
					Intent intent = new Intent();
					intent.setClass(CouponSearchActivity.this, CaptureActivity.class);
					CouponSearchActivity.this.startActivity(intent);
					overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				}else{
					CouponSearchActivity.this.startActivity(new Intent(CouponSearchActivity.this,CouponLoginActivity.class));
				}
				return false;
			}
		});
    	
    	myCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponSearchActivity.this, MyCouponListActivity.class);
				CouponSearchActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    }
    
//    private void dynamicChangeLayout(){
//    	ScrollView contentScrollView = (ScrollView) linearLayout.findViewById(R.id.contentScrollView);
//        RelativeLayout titleRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.titleRelativeLayout);
//        RelativeLayout footerRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.footerRelativeLayout);
        
//    	LayoutParams contentLayoutParams = contentScrollView.getLayoutParams();
//      //獲取屏幕高度
//      DisplayMetrics displayMetrics = new DisplayMetrics();
//      getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//      Integer contentScrollViewHeight = displayMetrics.heightPixels;
//      
//      contentLayoutParams.height = contentScrollViewHeight - titleRelativeLayout.getLayoutParams().height - footerRelativeLayout.getLayoutParams().height - 30;
//      
//      contentScrollView.setLayoutParams(contentLayoutParams);
//    }
    
    @SuppressWarnings("unchecked")
	private List getCityList(){
    	List<Map> cityList = new ArrayList<Map>();

    	Map map1 = new HashMap();map1.put("cityId", 1);map1.put("cityName","臺北市");cityList.add(map1);
    	Map map2 = new HashMap();map2.put("cityId", 2);map2.put("cityName","基隆市");cityList.add(map2);
    	Map map3 = new HashMap();map3.put("cityId", 3);map3.put("cityName","臺北縣");cityList.add(map3);
    	Map map4 = new HashMap();map4.put("cityId", 4);map4.put("cityName","宜蘭縣");cityList.add(map4);
    	Map map5 = new HashMap();map5.put("cityId", 5);map5.put("cityName","桃園縣");cityList.add(map5);
    	Map map6 = new HashMap();map6.put("cityId", 6);map6.put("cityName","新竹市");cityList.add(map6);
    	Map map7 = new HashMap();map7.put("cityId", 7);map7.put("cityName","新竹縣");cityList.add(map7);
    	Map map8 = new HashMap();map8.put("cityId", 8);map8.put("cityName","苗栗縣");cityList.add(map8);
    	Map map9 = new HashMap();map9.put("cityId", 9);map9.put("cityName","臺中縣");cityList.add(map9);
    	Map map10 = new HashMap();map10.put("cityId", 10);map10.put("cityName","臺中市");cityList.add(map10);
    	Map map11 = new HashMap();map11.put("cityId", 11);map11.put("cityName","彰化縣");cityList.add(map11);
    	Map map12 = new HashMap();map12.put("cityId", 12);map12.put("cityName","南投縣");cityList.add(map12);
    	Map map13 = new HashMap();map13.put("cityId", 13);map13.put("cityName","雲林縣");cityList.add(map13);
    	Map map14 = new HashMap();map14.put("cityId", 14);map14.put("cityName","嘉義市");cityList.add(map14);
    	Map map15 = new HashMap();map15.put("cityId", 15);map15.put("cityName","嘉義縣");cityList.add(map15);
    	Map map16 = new HashMap();map16.put("cityId", 16);map16.put("cityName","臺南市");cityList.add(map16);
    	Map map17 = new HashMap();map17.put("cityId", 17);map17.put("cityName","臺南縣");cityList.add(map17);
    	Map map18 = new HashMap();map18.put("cityId", 18);map18.put("cityName","高雄市");cityList.add(map18);
    	Map map19 = new HashMap();map19.put("cityId", 19);map19.put("cityName","高雄縣");cityList.add(map19);
    	Map map20 = new HashMap();map20.put("cityId", 20);map20.put("cityName","屏東縣");cityList.add(map20);
    	Map map21 = new HashMap();map21.put("cityId", 21);map21.put("cityName","澎湖縣");cityList.add(map21);
    	Map map22 = new HashMap();map22.put("cityId", 22);map22.put("cityName","臺東縣");cityList.add(map22);
    	Map map23 = new HashMap();map23.put("cityId", 23);map23.put("cityName","花蓮縣");cityList.add(map23);
    	Map map24 = new HashMap();map24.put("cityId", 24);map24.put("cityName","金門縣");cityList.add(map24);
    	Map map25 = new HashMap();map25.put("cityId", 25);map25.put("cityName","連江縣");cityList.add(map25);
    	
    	return cityList;
    }
}